<script setup lang="ts">
import { computed, onMounted, ref } from "vue";
import { useRouter } from "vue-router";
import { showFailToast, showSuccessToast, showToast } from "vant";
import { cancelBindMobilAPI } from "@/api/userApi.ts";
import type { Ref, ComputedRef } from "vue";
import type { FormInstance, FieldValidateError } from "vant";
import type { Router } from "vue-router";
import useUserStore from "@/pinia/modules/userStore.ts";
import useCountdown from "@/hooks/useCountdown.ts";
import { mobileRules, codeRules, passwordRules } from "@/validate";
import Tips from "@/views/login/components/Tips/Tips.vue";
import useSendCode from "@/hooks/useSendCode.ts";

const userStore = useUserStore();
const router: Router = useRouter();
/*手机号*/
const mobile: Ref<string> = ref<string>("13230000002");
/*密码*/
const password: Ref<string> = ref<string>("abc12345");
/*验证码*/
const code: Ref<string> = ref<string>("");
/*是否勾选协议*/
const isAgree: Ref<boolean> = ref(true);
/*loading状态*/
const loading: Ref<boolean> = ref<boolean>(false);
/*是否是验证码登录*/
const isCodeLogin: Ref<boolean> = ref<boolean>(false);
/*vant-form组件实例*/
const formInstance: Ref<FormInstance | null> = ref<FormInstance | null>(null);
/*密码框的类型*/
const passwordType: Ref<"password" | "text"> = ref<"password" | "text">("password");
/*svg-icon的名称*/
const svgName: ComputedRef<"eye" | "eye-open"> = computed<"eye" | "eye-open">(() => passwordType.value === "password" ? "eye" : "eye-open");

const { countdown, start, subCountdown } = useCountdown(60);

const { code: codeNumber, sendCode: onSendCode } = useSendCode();

/*发送验证码按钮的回调函数*/
const sendCode = async () => {
    // 验证码单个表单项
    const valida: FieldValidateError | undefined = await formInstance.value?.validate("mobile").catch(error => error);
    // 返回一个对象则证明校验失败
    if (valida) return showToast({ type: "fail", message: valida.message });
    // 开启倒计时
    subCountdown();
    try {
        // 发送验证码并且将验证码结果赋值给code的ref响应式对象
        // code.value = await userStore.sendCode({ mobile: mobile.value, type: "login" });
        await onSendCode({ mobile: mobile.value, type: "login" });
        code.value = codeNumber.value;
    } catch (error: any) {
        // 发送验证码失败
        showToast({ type: "fail", message: error.message });
    }
};


/*表单校验通过的回调函数*/
const handleSubmit = async () => {
    // 判断用户是否勾选协议，如果没有勾选协议则return出去
    if (!isAgree.value) return showToast({ message: "请勾选协议" });
    // 密码登录或者是验证码登录的提示消息
    let message = "";
    // 开启loading效果
    loading.value = true;
    try {
        if (isCodeLogin.value) {
            // 验证码登录
            message = await userStore.codeLogin({ mobile: mobile.value, code: code.value });
        } else {
            // 密码登录
            message = await userStore.passwordLogin({ mobile: mobile.value, password: password.value });
        }
        // 提示用户登录成功
        showToast({ type: "success", message });
        // 路由跳转
        await router.push("/");
    } catch (error: any) {
        // 提示用户登录失败
        showToast({ type: "fail", message: error.message });
    } finally {
        // 请求完成关闭loading效果
        loading.value = false;
    }
};

/*表单校验失败的回调函数*/
const handleFailed = ({ errors }: { errors: FieldValidateError[] }): void => {
    showToast({ type: "fail", message: errors[0].message });
};


/*切换密码框类型的回调函数*/
const changePasswordType = (): void => {
    passwordType.value = passwordType.value === "password" ? "text" : "password";
};


/*解除绑定的按钮*/
const onCancelBindMobil = async () => {
    try {
        await cancelBindMobilAPI(mobile.value);
        showSuccessToast("解绑成功");
    } catch (error) {
        showFailToast("解绑失败");
    }
};

onMounted(() => {
    /*
    组件渲染完毕，使用QC生成QQ登录按钮，目的得到跳转链接
    QC.Login({
        btnId: "qq",
    })
    */
});

</script>

<template>
    <div class="login">
        <!--顶部导航栏-->
        <nav-bar left-text="返回" title="登录" right-text="优医问诊" left-arrow></nav-bar>
        <!--背景图-->
        <div class="bg"><img src="@/assets/images/loginBg.jpg"></div>
        <tips v-model="isCodeLogin"></tips>
        <!--表单-->
        <van-form label-width="15px" show-error ref="formInstance" :show-error-message="false" @submit="handleSubmit" @failed="handleFailed">

            <van-field placeholder="请输入手机号" v-model="mobile" name="mobile" :rules="mobileRules">
                <template #label>
                    <svg-icon svg-name="mobile" width="20px" height="20px"></svg-icon>
                </template>
            </van-field>

            <van-field placeholder="请输入密码" :type="passwordType" name="password" v-model="password" v-if="!isCodeLogin" :rules="passwordRules">
                <template #label>
                    <svg-icon svg-name="password" width="20px" height="20px"></svg-icon>
                </template>
                <template #right-icon>
                    <svg-icon :svg-name="svgName" width="15px" height="15px" @click="changePasswordType"></svg-icon>
                </template>
            </van-field>

            <van-field placeholder="请输入验证码" v-model="code" name="code" v-else :rules="codeRules">
                <template #label>
                    <svg-icon svg-name="code" width="20px" height="20px"></svg-icon>
                </template>
                <template #right-icon>
                    <van-button round size="mini" type="primary" :disabled="start" @click="sendCode">{{ start ? `${countdown}S后重新发送` : `发送验证码` }}</van-button>
                </template>
            </van-field>

            <div class="cell">
                <van-checkbox v-model="isAgree"><span>我已同意</span><a>用户协议</a><span>及</span><a>隐私条款</a></van-checkbox>
            </div>


            <div class="cell button">
                <van-button block round :loading="loading" native-type="submit" type="primary">登 录</van-button>
            </div>


            <div class="other">
                <van-divider>第三方登录</van-divider>
                <a href="https://graph.qq.com/oauth2.0/authorize?client_id=102015968&response_type=token&scope=all&redirect_uri=http%3A%2F%2Fconsult-patients.itheima.net%2Flogin%2Fcallback" class="icon">
                    <img src="@/assets/images/qq.svg" alt="" />
                </a>
            </div>
        </van-form>

        <p>手机号:13230000001 - 13230000100</p>
        <p>密码:abc12345</p>
        <p @click="onCancelBindMobil" class="cancel">解除手机绑定</p>

    </div>
</template>

<style scoped lang="scss">
@import "@/styles/login";

</style>
